//
//  TXUserAccountViewModel.swift
//  MicroBlog
//
//  Created by Jokin on 2017/3/29.
//  Copyright © 2017年 jokin. All rights reserved.
//

import UIKit

class TXUserAccountViewModel: NSObject {
    static let shareUserViewModel: TXUserAccountViewModel = TXUserAccountViewModel()
    
    func requestAcceesToken(code: String, callBack: @escaping (Bool) ->()) {
        
        NetWorkTools.sharedTools.requestAccessToken(code: code) { (resbounce, error) in
            
            if error != nil {
                print("网络请求异常\(error)")
                callBack(false)
                return
            }
            
            guard let dic = resbounce as? [String :Any] else {
                print("返回的格式不对")
                callBack(false)
                return
            }
            
            let model = TXUserAccount(dic: dic)
            self.requestUserAccount(userAccount: model, callBack: callBack)
            
            
            
        }
        
        
        
        
    }
    
    fileprivate override init() {
        userAccount = TXUserAccount.loadUserAccount()
    }
    
    var accessToken :String? {
        if userAccount?.expirceDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return userAccount?.access_token
        }
        return nil
    }
    var isLogin : Bool {
     return userAccount != nil
        
    }
    
    
    var userAccount : TXUserAccount?
    
    func requestUserAccount(userAccount: TXUserAccount, callBack:@escaping (Bool) ->()) {
        let acccount = userAccount.access_token!
        let uid = userAccount.uid
        NetWorkTools.sharedTools.requestUserInfo(token: acccount, uid: uid) { (response, error)  in
            if error != nil {
                callBack(false)
                return
            }
            
            guard let obj = response as? [String : Any] else {
                callBack(false)
                return
            }
            let name = obj["name"] as? String
            let avatar_large = obj["avatar_large"] as? String
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            userAccount.saveAcoder()
            self.userAccount = userAccount
            callBack(true)
        }
        
        
    }

}
